import Ol from "./ClassOl";
import tools from "../tools";
import createBaseLayer from "../baseLayers";
import { mapMouseMove } from "../mapMouseMove";

/**
 * @description: 用于创建地图实例对象
 * @return {*}
 * @Author: yx
 */
class ScreenMap extends Ol {
  constructor() {
    super();
    this.center = [120.5, 29];
    this.createBaseLayer = createBaseLayer;
    this.mapMouseMove = mapMouseMove;
    this.initTools();
  }

  /**
   * @description: 初始化工具方法
   * @return {*}
   * @Author: yx
   */
  initTools() {
    Object.keys(tools).forEach((key) => {
      this[key] = tools[key];
    });
  }

  /**
   * @description: 初始化地图
   * @param {String(目标Dom容器id)} target
   * @param {Ol.Layer} layers
   * @return {*}
   * @Author: yx
   */
  init(target, layers) {
    if (!target) {
      throw new Error("请传入参数target（目标容器）！");
    }
    this.map = new this.Map({
      // 视图
      view: new this.View({
        center: this.center,
        zoom: 7,
        projection: "EPSG:4326",
      }),
      // 图层
      layers,
      // 目标容器
      target,
      // 控件
      controls: this.defaultControls({
        zoom: false,
        rotate: false,
        attribution: false,
      }),
    });
  }

  /**
   * @description: 添加多个图层
   * @param {Array[Ol.Layer]} layers
   * @return {*}
   * @Author: yx
   */
  addLayers(layers) {
    if (!layers instanceof Array) throw new Error("请传入数组类型的图层");
    layers.forEach((layer) => {
      if (layer) {
        this.map.addLayer(layer);
      } else {
        throw new Error("请检查传入图层是否正确！");
      }
    });
  }

  /**
   * @description: 地图定位
   * @param {String} lon
   * @param {String} lat
   * @param {Number} zoom
   * @return {*}
   * @Author: yx
   */
  locate(lon, lat, zoom) {
    if (!lon || !lat) {
      throw new Error("请传入经纬度！");
    }
    let lonStr = lon.toString();
    let latStr = lat.toString();
    this.map.getView().animate({
      center: [lonStr, latStr],
      zoom: zoom || 10,
      duration: 500,
    });
  }

  /**
   * @description: 清除底图外图层
   * @return {*}
   * @Author: yx
   */
  removeLayers() {
    let customLayers = this.map
      .getLayers()
      .getArray()
      .filter((layer) => {
        return !layer.get("isBase"); //判断依据，是否包含isBase属性
      });
    if (!customLayers) {
      return false;
    }
    customLayers.forEach((l) => {
      this.map.removeLayer(l);
    });
  }
}
export default ScreenMap;
